(ns ken.pu.web.core
  (:use compojure.core
        ring.adapter.jetty
        ken.pu.lucene-helper
        ken.pu.web.search)
  (:require [compojure.route :as route])
  (:require [compojure.handler :as handler]))

(defn jsonp?
  "Returns true if a callback function exists, false if it does not."
  [callback]
  (not-empty callback))

(defn ret-js
  "Returns JavaScript in either JSON or JSONP form, depending on whether or not
    a callback is specified.  It should automagically specify the correct header
    information as well as body content."
  [data callback]
  (let [jsonp (jsonp? callback)]
    {:status 200
     :headers {"Content-Type"
               (if jsonp
                 "application/javascript"
                 "application/json")}
     :body
        (if jsonp
          (jsonpify data callback)
          (jsonify data))}))

(defroutes main-routes
  (GET "/" [] "<p>What are you doing here?  Go away!</p>")
  (GET "/suggest/"
    [q callback]
    (ret-js (suggest-fuzzy q) callback))
  (GET "/search/"
    [q callback]
    (ret-js (search q 5) callback))
  (route/not-found "<h1>Page not found</h1>"))

(def *app*
  (handler/site main-routes))

(run-jetty *app* {:port 8000})